import React, { useEffect, useRef, useState } from 'react';
import {
  PageContainer,
  ProFormInstance,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { history, request, useModel } from '@umijs/max';
import { useSearchParams } from '@@/exports';
import baseForm from '@/pages/Goods/SaveOrUpdate/components/BaseForm';
import { Goods } from '@/types/business';


function getGoodsInfo(id: number | string) {
  console.log(id, '???');
  return request('/admin/goods/getOne', {
    method: 'post',
    params: {
      id
    }
  })
}



function detailForm() {
  return (
    <div>详情表单</div>
  )
}

export default function Page() {
  const [searchParams] = useSearchParams()
  const formRef = useRef<ProFormInstance>()
  const { setFileList } = useModel('Goods.SaveOrUpdate.components.model')
  const [initData, setInitData] = useState<Goods>()

  /**
   *  提交表单
   */
  const handleSubmit = async () => {
    await formRef.current?.validateFields()
    let postData = null
    if(searchParams.get('type') === 'edit') {
      console.log('编辑提交');
      // @ts-ignore
      postData = formRef.current?.getFieldFormatValue();
    } else {
      postData = formRef.current?.getFieldFormatValue?.();
    }


    request('/admin/goods/saveOrUpdateGoods', {
      method: 'post',
      data: postData
    }).then(res => {
      if(res.data) {
        message.success('操作成功')
        history.back()
      }
    })
  }

  useEffect(  () => {
    console.log('props', searchParams);
    const type = searchParams.get('type');
    console.log('type', type);
    setFileList([])
    if (type === 'edit') {
      getGoodsInfo(searchParams.get('id') as string).then(res => {
        formRef.current?.setFieldsValue(res.data)
        setInitData(res.data)
        request('/tools-file/query', {
          params: {
            modelCode: 'MA001',
            busiKey: res.data.picKey
          },
          method: 'post'
        }).then(files => {
          setFileList(files.data)
        })
      })
    } else {
      request('/tools/getSnowflakeId').then(res => {
        setInitData((prevState) => ({
          ...prevState,
          picKey: res.data
        }))
        formRef.current?.setFieldValue('picKey', res.data)
      })
    }
  }, []);

  return (
    <PageContainer
      title={searchParams.get('type') === 'add' ? '新增商品' : '编辑商品'}
      header={{
        onBack: () => window.history.back(),
      }}
      tabList={[
        {
          tab: '基本信息',
          key: 'base',
          children: baseForm({formRef, fileKey: initData?.picKey})
        },
        {
          tab: '商品详情',
          key: 'detail',
          children: detailForm()
        }
      ]}
      footer={[
        <Button key="3" onClick={() => history.back()}>取消</Button>,
        <Button key="2" type="primary" onClick={() => handleSubmit()}>
          提交
        </Button>,
      ]}
    >
    </PageContainer>
  );
}
